#include<iostream>
#include<vector>
#include<cstring>
using namespace std;
int t, n, a;
int arr[105000];
int main()
{
	cin >> t;
	while (t--) {
		memset(arr, 0, sizeof(arr));
		cin >> n >> a;
		arr[1] = 1;
		int len = 1;
		for (int i = 2; i <= n; i++) {
			int jw = 0;
			for (int j = 1; j <= len; j++) {
				arr[j] = arr[j] * i + jw;
				jw = arr[j] / 10;
				arr[j] %= 10;
			}
			while (jw) {
				arr[++len] = jw % 10;
				jw /= 10;
			}
		}
		long long count = 0;
		for (int i = len ; i >= 1; i--) {
			if (arr[i] == a) {
				count++;
			}
		}
		cout << count << endl;
	}
	return 0;
}